import { Module } from 'vuex'

import localCache from '@/utils/cache'
import router from '@/router'

import { IAccount } from '@/service/login/type'
import { ILoginState } from './type'
import { IRootState } from '../type'
import { accountLoginRequest, listRoleMenu } from '@/service/login/login'
import { menusToRoutes, menuMapToPermissions } from '@/utils/menus2routes'
import { ElMessage } from 'element-plus'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      roleMenus: [],
      permissions: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, roleMenus: any) {
      state.roleMenus = roleMenus
      //注册动态路由
      const routes = menusToRoutes(roleMenus)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      //检查按钮权限
      const permissions = menuMapToPermissions(roleMenus)
      state.permissions = permissions
    }
  },
  actions: {
    //同步方法异步请求
    async accountLoginAction({ commit }, payload: IAccount) {
      //登录
      const loginResult = await accountLoginRequest(payload)
      if (loginResult.data.code === 20000) {
        const { name, roleId, userId, url, email, token } =
          loginResult.data.data

        if (roleId > 2) {
          //必须提交到mutation
          commit('changeToken', token)
          localCache.setCache('token', token)
          const userInfo = { name, roleId, userId, url, email }
          commit('changeUserInfo', userInfo)
          localCache.setCache('userInfo', userInfo)

          //获取用户权限菜单
          const roleMenu = await listRoleMenu(roleId)
          const roleMenus = roleMenu.data.data
          commit('changeUserMenus', roleMenus)
          localCache.setCache('roleMenus', roleMenus)

          //跳转到首页
          router.push('/main')
        } else {
          ElMessage.warning('No administrator privileges')
          router.push('/login')
        }
      } else {
        switch (loginResult.data.code) {
          case 10001:
            ElMessage.error('account does not exist')
            break
          case 10002:
            ElMessage.error('check the password')
            break
          case 10003:
            ElMessage.error('account deleted')
            break
          case 10004:
            ElMessage.error('account limited')
            break
          case 10005:
            ElMessage.error('account needs to be re registered')
            break
          default:
            ElMessage.error('login failed')
            break
        }
        router.push('/login')
      }
    },
    //防止刷新导致vuex数据丢失
    loadLocalLogin({ commit }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('changeToken', token)
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const roleMenus = localCache.getCache('roleMenus')
      if (roleMenus) {
        commit('changeUserMenus', roleMenus)
      }
    }
  }
}
export default loginModule
